import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    goodList: [
      {
        name: '诸葛亮',
        price: 1000,
        num: 1,
        checked: false
      },
      {
        name: '蔡文姬',
        price: 1500,
        num: 1,
        checked: false
      },
      {
        name: '妲己',
        price: 2000,
        num: 1,
        checked: false
      },
      {
        name: '鲁班',
        price: 2200,
        num: 1,
        checked: false
      }
    ]
  },
  mutations: {
    addNum (state, payload) {
      state.goodList[payload].num++
    },
    subNum (state, payload) {
      state.goodList[payload].num--
    },
    delList (state, payload) {
      state.goodList.splice(payload, 1)
    },
    // 全选反选
    ChangeInput (state, payload) {
      state.goodList.forEach(item => (item.checked = payload))
    },
    addList (state, payload) {
      state.goodList.push(payload)
    }
  },
  actions: {
  },
  getters: {
    total: (state) => (index) => {
      return (state.goodList[index].price * state.goodList[index].num)
    },
    totalPrice: (state) => {
      return state.goodList.reduce((sum, item) => {
        if (item.checked) {
          sum += item.price * item.num
        }
        return sum
      }, 0)
    },
    isAll: (state) => {
      return (state.goodList.every(item => item.checked))
    }
  }
})
